# -*- coding: utf-8 -*-
import xlrd
import xlwt
# import xlutils
import pymysql
from datetime import date,datetime

# 从mysql中获取多条记录
def mysql_list_items(sql):
    conn = pymysql.connect(host='127.0.0.1',port=3306, user='root', password='19751128',db='stock',charset='utf8')
    cur = conn.cursor()
    cur.execute(sql)
    data = cur.fetchall()
    cur.close()
    conn.close()
    # for item in data:
    #     print(item)
    return data

# 从mysql中获取单条记录
def mysql_single_item(sql):
    conn = pymysql.connect(host='127.0.0.1',port=3306, user='root', password='19751128',db='stock',charset='utf8')
    cur = conn.cursor()
    cur.execute(sql)
    data = cur.fetchone()
    cur.close()
    conn.close()
    # print(data)
    return data

# 从excel中读取
def read_excel():
    # 文件位置
    ExcelFile = xlrd.open_workbook(r'C:\Users\Administrator\Desktop\test.xls')
    # 获取目标EXCEL文件sheet名
    print(ExcelFile.sheet_names())
    # ------------------------------------
    # 若有多个sheet，则需要指定读取目标sheet例如读取sheet2
    # sheet2_name = ExcelFile.sheet_names()[1]
    # ------------------------------------
    # 获取sheet内容【1.根据sheet索引2.根据sheet名称】
    sheet = ExcelFile.sheet_by_index(0)
    # sheet = ExcelFile.sheet_by_name('TestCase002')
    # 打印sheet的名称，行数，列数
    sheetName = sheet.name
    sheetRows = sheet.nrows
    sheetCols = sheet.ncols
    print('表名：',sheetName)
    print('行数：',sheetRows)
    print('列数：',sheetCols)
    i = 0
    # 获取整行或者整列的值
    while i < sheetRows:
        # cols = sheet.col_values(i)#第1列内容
        rows = sheet.row_values(i)#第1行内容
        i += 1
        # print(cols,rows)
        print(rows)
    # 获取单元格内容
    # print(sheet.cell(1,0).value.encode('utf-8'))
    # print(sheet.cell_value(1,0).encode('utf-8'))
    # print(sheet.row(1)[0].value.encode('utf-8'))
    # 打印单元格内容格式
    # print(sheet.cell(1,0).ctype)

#写数据
def write_excel(filename, data):
    book = xlwt.Workbook()            #创建excel对象
    sheet = book.add_sheet('sheet1')  #添加一个表
    c = 0  #保存当前列
    for d in data: #取出data中的每一个元组存到表格的每一行
        for index in range(len(d)):   #将每一个元组中的每一个单元存到每一列
            sheet.write(c,index,d[index])
        c += 1
    book.save(filename) #保存excel

if __name__ =='__main__':
     # read_excel()
     # mysql_list_items('SELECT * FROM py')
     # mysql_single_item('SELECT * FROM py LIMIT 1')
     res = mysql_list_items('SELECT * FROM py')
     write_excel(r'C:\Users\Administrator\Desktop\firstsheet.xls', res)